<template>
  <el-dialog
      title="导出JSON"
      :with-header="false"
      :visible.sync="visible"
      :close-on-click-modal="true"
      custom-class="layer_wrap add-endorse"
      :before-close="()=>handleClose('ruleForm')">
    <div class="layer_inside">
      <div class="layer_header">
        <span class="title">导出JSON</span>
        <i class="el-icon-close" @click="()=>handleClose('ruleForm')"/>
      </div>
      <div class="layer_main_wrap">
        <div class="layer_main_inside">
          <div class="ace-container" v-if="visible">
            <div class="ace-editor" ref="ace"></div>
          </div>
        </div>
        <div class="button-area" v-if="false">
          <el-row class="el-form-button-inside">
            <el-col :span="12">
              <el-button size="small" @click="handleClose('ruleForm')">取消</el-button>
            </el-col>
            <el-col :span="12">
              <el-button size="small" type="primary" @click="handleSubmit('ruleForm')">发布</el-button>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import ace from 'ace-builds';
/*
启用此行后webpack打包回生成很多动态加载的js文件，不便于部署，故禁用！！
特别提示：禁用此行后，需要调用ace.config.set('basePath', 'path...')指定动态js加载URL！！
*/
// import 'ace-builds/webpack-resolver'
import 'ace-builds/src-min-noconflict/theme-sqlserver' // 新设主题
import 'ace-builds/src-min-noconflict/mode-javascript' // 默认设置的语言模式
import 'ace-builds/src-min-noconflict/mode-json'
import 'ace-builds/src-min-noconflict/mode-css'
import 'ace-builds/src-min-noconflict/ext-language_tools'
import {ACE_BASE_PATH} from "@/utils/designer/config";
import {ModelDesignApi} from "@/api/modeldesign";

export default {
  name: 'CodeEditor',

  props: {
    visible: {
      type: Boolean,
      required: true,
      default: false
    },
    info: {
      type: String,
      required: true
    },
    readonly: {
      type: Boolean,
      default: false
    },
    mode: {
      type: String,
      default: 'javascript'
    },
    //是否开启语法检查，默认开启
    userWorker: {
      type: Boolean,
      default: true
    },
  },

  data() {
    return {
      aceEditor: null,
      themePath: 'ace/theme/sqlserver', // 不导入 webpack-resolver，该模块路径会报错
      modePath: 'ace/mode/javascript', // 同上
      codeValue: this.value
    }
  },

  computed: {
    templateInfo() {
      return this.$store.getters['templateDetails/getTemplateInfo']
    }
  },

  mounted() {
    ace.config.set('basePath', ACE_BASE_PATH)
  },

  methods: {
    // 初始化ACE组件库
    initJSONACE() {
      const self = this;
      //添加自定义代码提示！！
      self.addAutoCompletion(ace)
      if (self.$refs.ace) {
        self.aceEditor = ace.edit(this.$refs.ace, {
          maxLines: 20, // 最大行数，超过会自动出现滚动条
          minLines: 5, // 最小行数，还未到最大行数时，编辑器会自动伸缩大小
          fontSize: 12, // 编辑器内字体大小
          theme: this.themePath, // 默认设置的主题
          mode: this.modePath, // 默认设置的语言模式
          tabSize: 2, // 制表符设置为2个空格大小
          readOnly: this.readonly,
          highlightActiveLine: true,
          value: this.info,
        })
        self.aceEditor.setOptions({
          enableBasicAutocompletion: true,
          enableSnippets: true,  // 设置代码片段提示
          enableLiveAutocompletion: true,  // 设置自动提示
        })

        if (self.mode === 'json') {
          self.setJsonMode()
        } else if (self.mode === 'css') {
          self.setCssMode()
        }

        if (!self.userWorker) {
          self.aceEditor.getSession().setUseWorker(false)
        }

        //编辑时同步数据
        self.aceEditor.getSession().on('change', (ev) => {
          self.$emit('input', this.aceEditor.getValue())
        })
      }
    },

    addAutoCompletion(ace) {
      let acData = [
        {meta: 'VForm API', caption: 'getWidgetRef', value: 'getWidgetRef()', score: 1},
        {meta: 'VForm API', caption: 'getFormRef', value: 'getFormRef()', score: 1},
        //TODO: 待补充！！
      ]
      let langTools = ace.require('ace/ext/language_tools')
      langTools.addCompleter({
        getCompletions: function (editor, session, pos, prefix, callback) {
          if (prefix.length === 0) {
            return callback(null, []);
          } else {
            return callback(null, acData);
          }
        }
      })
    },

    setJsonMode() {
      this.aceEditor.getSession().setMode('ace/mode/json')
    },

    setCssMode() {
      this.aceEditor.getSession().setMode('ace/mode/css')
    },

    getEditorAnnotations() {
      return this.aceEditor.getSession().getAnnotations()
    },

    // 关闭
    handleClose() {
      this.$emit("handleCancel", false);
    },

    // 发布
    async handleSubmit() {
      let paramsInfo = Object();
      let {params} = (this.$route);
      let {formConfig, widgetList} = JSON.parse(this.info);
      if ((params.type) === 'create') {
        let templateInfo = localStorage.getItem('templateInfo');
        let tempInfo = JSON.parse(templateInfo)
        Reflect.set(paramsInfo, 'title', (tempInfo.title));
        Reflect.set(paramsInfo, 'devType', (tempInfo.devType));
        Reflect.set(paramsInfo, 'bizType', (tempInfo.bizType) || 0);
        Reflect.set(paramsInfo, 'resolution', (tempInfo.resolution));
        Reflect.set(paramsInfo, 'formConfig', JSON.stringify(formConfig));
        Reflect.set(paramsInfo, 'widgetList', JSON.stringify(widgetList));
        let {code} = await ModelDesignApi.createHtml(paramsInfo);
        if (code === 200) {
          console.log('修改成功')
          this.$emit("handleCancel", false);
        } else {
          console.log('修改失败')
        }
      } else if ((params.type) === 'detail') {
        console.log('detail')
        let templateInfo = (this.templateInfo);
        Reflect.set(templateInfo, 'formConfig', JSON.stringify(formConfig));
        Reflect.set(templateInfo, 'widgetList', JSON.stringify(widgetList))
        let {code} = await ModelDesignApi.createHtml(templateInfo);
        if (code === 200) {
          console.log('修改成功')
          this.$emit("handleCancel", false);
        } else {
          console.log('修改失败')
        }
      }
    },


  },

  watch: {
    // 初始化
    visible: {
      handler(val) {
        const self = this;
        if (val) {
          self.$nextTick(() => {
            self.initJSONACE();
          })
        }
      },
      deep: false,
      immediate:true,
    }
  }

}
</script>

<style lang="scss" scoped>
@import "@a/style/layer";

.ace-editor {
  min-height: 300px;
}
</style>
